package com.albert.controller;

import com.albert.entity.Product;
import com.albert.mapper.ProductMapper;
import com.albert.service.ProductService;
import com.albert.utils.HttpClientAuthUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductMapper mapper;
    @Autowired
    private ProductService service;
    //@Value("${oms.httpclient.userName}")
    private String userName;

    //@Value("${oms.httpclient.password}")
    private String password;

    @GetMapping("/page")
    public List<Product> getProductByPage(Integer page, Integer pageSize) {
        Page<Product> proPage = new Page<>(page, pageSize);
        mapper.selectPage(proPage, null);
        List<Product> records = proPage.getRecords();
        long total = proPage.getTotal();
        System.out.println("总条数" + total);
        return records;
    }

    //发送HTTP请求调用第三方接口,获取分页查询的数据
    @GetMapping("/from")
    public String selectThird() {
        // 第三方接口的基础 URL
        String baseUrl = "http://localhost:8080/product/page";
        // 每页的数量
        int pageSize = 10;
        boolean hasMoreData = true;
        int page = 1;
        while (hasMoreData) {
            // 构建请求的 URL
            String url = baseUrl + "?page=" + page + "&pageSize=" + pageSize;
            HttpClientAuthUtils authUtils = new HttpClientAuthUtils();
            HashMap<String, String> paramMap = new HashMap<>();
            paramMap.put("userName", userName);
            paramMap.put("password", password);
            String body = authUtils.sendGet(url, null, paramMap);
            System.out.println(body);
            //对数据进行解析
            List<Product> products = JSON.parseArray(body, Product.class);
            if (products.size() > 0) {
                //批量保存
                System.out.println("备注,开始执行批量转存数据");
                //service.saveBatch(products);
                page++;
            } else {
                hasMoreData = false;
            }
        }
        return "链接第三方成功并且转存数据成功";
    }

}
